package org.devops

// checkout代码
def checkout(gitAddress, branch, credentialId) {
    checkout([$class : 'GitSCM',
              branches: [[name: "${branch}"]],
              extensions: [],
              userRemoteConfigs: [
                      [credentialsId: "${credentialId}", url: "${gitAddress}"]
              ]
    ])

    env.gitCommitId = sh (script: 'git rev-parse HEAD', returnStdout: true).trim()
    env.gitShortCommitId = sh (script: 'git rev-parse --short HEAD', returnStdout: true).trim()

    return env.gitShortCommitId;
}

// 封装HTTP请求
def httpReq(method, reqUrl, reqBody) {
    def gitlabApiRoot = "https://gitlab.devops.com/api/v4"
    def gitlabTokenId = "gitlab-token"
    withCredentials([string(credentialsId: "${gitlabTokenId}", variable: 'gitlabToken')]) {
        result = httpRequest httpMode: method, url: "${gitlabApiRoot}/${reqUrl}",
                customHeaders: [[maskValue: true, name: 'PRIVATE-TOKEN', value: gitlabToken]],
                contentType: 'APPLICATION_JSON_UTF8',
                requestBody: reqBody,
                quiet: true,
                ignoreSslErrors: false,
                acceptType: 'APPLICATION_JSON_UTF8',
                consoleLogResponseBody: false
    }
    return result
}

// 更改提交状态
def setCommitStatus(status) {
    if (env.triggerFrom == "gitlab") {
        commitApi = "projects/${env.projectId}/statuses/${env.gitCommitId}?state=${status}"
        response = httpReq('POST', commitApi, '')
        println(response)
    }
}

// 更新文件内容
def updateRepoFile(projectId, filePath, fileContent) {
    apiUrl = "projects/${projectId}/repository/files/${filePath}"
    reqBody = """{"branch": "master","encoding":"base64", "content": "${fileContent}", "commit_message": "update a new file"}"""
    response = httpReq('PUT', apiUrl, reqBody)
    println(response)
}

// 获取文件内容
def getRepoFile(projectId, filePath) {
    apiUrl = "projects/${projectId}/repository/files/${filePath}/raw?ref=master"
    response = httpReq('GET', apiUrl, '')
    return response.content
}

// 创建仓库文件
def createRepoFile(projectId, filePath, fileContent) {
    apiUrl = "projects/${projectId}/repository/files/${filePath}"
    reqBody = """{"branch": "master","encoding":"base64", "content": "${fileContent}", "commit_message": "create a new file"}"""
    response = httpReq('POST', apiUrl, reqBody)
    println(response)
}

// 获取项目ID
def getProjectID(repoName = '', projectName) {
    projectApi = "projects?search=${projectName}"
    response = httpReq('GET', projectApi, '')
    def result = readJSON text: """${response.content}"""

    for (repo in result) {
        // println(repo['path_with_namespace'])
        if (repo['path'] == "${projectName}") {

            repoId = repo['id']
            println(repoId)
        }
    }
    return repoId
}

// 删除分支
def deleteBranch(projectId, branchName) {
    apiUrl = "/projects/${projectId}/repository/branches/${branchName}"
    response = httpReq("DELETE", apiUrl, '').content
    println(response)
}

// 创建分支
def createBranch(projectId, refBranch, newBranch) {
    try {
        branchApi = "projects/${projectId}/repository/branches?branch=${newBranch}&ref=${refBranch}"
        response = httpReq("POST", branchApi, '').content
        branchInfo = readJSON text: """${response}"""
    } catch (e) {
        println(e)
    }  //println(branchInfo)
}

// 创建合并请求
def createPullRequest(projectId, sourceBranch, targetBranch, title, assigneeUser = "") {
    try {
        def mrUrl = "projects/${projectId}/merge_requests"
        def reqBody = """
                   {
                      "source_branch": "${sourceBranch}",
                      "target_branch": "${targetBranch}",
                      "title": "${title}",
                      "assignee_id": "${assigneeUser}"
                   }
                   """
        response = httpReq("POST", mrUrl, reqBody).content
        return response
    } catch (e) {
        println(e)
    }
}

// 搜索分支
def searchProjectBranches(projectId, searchKey) {
    def branchUrl = "projects/${projectId}/repository/branches?search=${searchKey}"
    response = httpReq("GET", branchUrl, '').content
    def branchInfo = readJSON text: """${response}"""

    def branches = [:]
    branches[projectId] = []
    if (branchInfo.size() == 0) {
        return branches
    } else {
        for (branch in branchInfo) {
            //println(branch)
            branches[projectId] += ["branchName": branch["name"],
                                    "commitMes" : branch["commit"]["message"],
                                    "commitId"  : branch["commit"]["id"],
                                    "merged"    : branch["merged"],
                                    "createTime": branch["commit"]["created_at"]]
        }
        return branches
    }
}

// 允许合并
def acceptMerge(projectId, mergeId) {
    def apiUrl = "projects/${projectId}/merge_requests/${mergeId}/merge"
    httpReq('PUT', apiUrl, '')
}
